﻿using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using ZHDJ.AppInterface.Common;
using ZHDJ.AppInterface.Models;
using ZHDJ.Core;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.DataCaching;

namespace ZHDJ.AppInterface
{
    public class CommonUtils
    {
        #region 计算总页数
        /// <summary>
        /// 计算总页数
        /// </summary>
        /// <param name="rowCount">总记录数</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns></returns>
        public static int GetTotalPages(int rowCount, int pageSize)
        {
            if (rowCount * pageSize == 0)
                return 0;

            return (rowCount / pageSize) + ((rowCount % pageSize) > 0 ? 1 : 0);
        }
        #endregion

        #region 分页查询语句
        /// <summary>
        /// 分页查询语句
        /// </summary>
        /// <param name="fields">查询字段</param>
        /// <param name="table">查询表</param>
        /// <param name="where">查询条件</param>
        /// <param name="order">排序</param>
        /// <param name="pageNo">必须大于０</param>
        /// <param name="pageCount">必须大于０</param>
        /// <returns></returns>
        public static DataSet QueryByPage(string fields, string table, string where, string order, int pageNo, int pageCount)
        {
            int firstNum = pageCount * (pageNo - 1);

            if (!string.IsNullOrEmpty(where))
                where = " where " + where;

            using (SqlCommand cmd = new SqlCommand())
            {
                string sql = string.Format(@"SELECT count(*) as recordCount from {1} {2};
                                            SELECT {0}  
                                            from {1} {2} order by {3} limit {4}, {5} ",
                                            fields, table, where, order, firstNum, pageCount);

                cmd.CommandText = sql;
                return ZHDJ.Data.MySqlHelper.ExecuteDataSet(cmd.CommandText);
            }
        }
        #endregion

        #region 添加接口日志
        /// <summary>
        /// 添加接口日志
        /// </summary>
        /// <param name="interfaceName">接口名称</param>
        /// <param name="InParam">入参</param>
        /// <param name="LogDesc">日志消息</param>
        /// <returns></returns>
        public static bool InsertMobileInterfaceLog(string interfaceName, string InParam, string LogDesc)
        {
            string sql = "";
            try
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = @"insert into tblPartyMobileInterfaceAccessLog(LogID,Logtime,InterfaceName,InParam,LogDesc)
                                             values(?LogID, now(), ?InterfaceName, ?InParam, ?LogDesc)";

                    MySqlParameter[] parameters = new MySqlParameter[]
                    {
                        new MySqlParameter("?LogID",MySqlDbType.VarChar),
                        new MySqlParameter("?InterfaceName",MySqlDbType.VarChar),
                        new MySqlParameter("?InParam",MySqlDbType.VarChar),
                        new MySqlParameter("?LogDesc",MySqlDbType.VarChar)
                    };
                    parameters[0].Value = StringHelper.NewID;
                    parameters[1].Value = interfaceName;
                    parameters[2].Value = InParam;
                    parameters[3].Value = LogDesc;

                    ZHDJ.Data.MySqlHelper.ExecuteNonQuery(cmd.CommandText, parameters);
                }
            }
            catch (Exception ex)
            {
                try
                {
                    StreamWriter sw = File.AppendText(ServiceSettings.LogFilePath + "MobileInterfaceLog_" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"));
                    sw.WriteLine(sql);
                    sw.WriteLine(ex.Message + ":" + ex.StackTrace);
                    sw.WriteLine();
                    sw.Close();
                    sw.Dispose();
                }
                catch
                {

                }
            }
            return true;
        }
        #endregion

        #region 图片上传接口
        /// <summary>
        /// 图片上传接口
        /// </summary>
        /// <param name="image">Base64字符编码图片</param>
        /// <param name="Extension">扩展名</param>
        /// <returns></returns>
        public static ImageModel UploadImagFile(string image, string Extension)
        {
            string returnPath = "upFile/";
            string filePath = HttpContext.Current.Server.MapPath("~/upFile"); //上传目录
            //string filePath = "http://shtdj.shanhaitian.gov.cn/AppInterface/upFile"; //上传目录
            if (!filePath.EndsWith("/")) filePath += "/";
            string fileName = StringHelper.NewID + "logo" + Extension;
            string nowDate = DateTime.Now.ToString("yyyy/MM/dd/");

            filePath += nowDate;
            returnPath += nowDate + fileName;
            string FullfileName = filePath + "/" + fileName;

            //图片转换
            string base64 = image.Replace("data:image/jpeg;base64,", "").Replace("data:image/jpg;base64,", "");

            byte[] imageByte = Convert.FromBase64String(base64);

            if (!Directory.Exists(filePath))//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(filePath);
            }
            //保存
            File.WriteAllBytes(FullfileName, imageByte);

            return new ImageModel()
            {
                ImageName = fileName,
                ImageUrl = returnPath
            };
        }
        #endregion

        #region 图片上传接口
        /// <summary>
        /// 图片上传接口
        /// </summary>
        /// <param name="image">Base64字符编码图片</param>
        /// <param name="Extension">扩展名</param>
        /// <returns></returns>
        public static ImageModel UploadImagFileExtend(string image, string Extension)
        {
            string returnPath = "upload/file/";
            //string filePath = HttpContext.Current.Server.MapPath("~/upFile"); //上传目录
            string filePath = "E:/ZHDJsite/web/upload/file";
            //string filePath = "http://shtdj.shanhaitian.gov.cn/AppInterface/upFile"; //上传目录
            if (!filePath.EndsWith("/")) filePath += "/";
            string fileName = StringHelper.NewID + "logo" + Extension;
            string nowDate = DateTime.Now.ToString("yyyyMMdd/");

            filePath += nowDate;
            returnPath += nowDate + fileName;
            string FullfileName = filePath + "/" + fileName;

            //图片转换
            string base64 = image.Replace("data:image/jpeg;base64,", "").Replace("data:image/jpg;base64,", "");

            byte[] imageByte = Convert.FromBase64String(base64);

            if (!Directory.Exists(filePath))//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(filePath);
            }
            //保存
            File.WriteAllBytes(FullfileName, imageByte);

            return new ImageModel()
            {
                ImageName = fileName,
                ImageUrl = returnPath
            };
        }
        #endregion

        #region 图片上传接口（加水印）
        /// <summary>
        /// 图片上传接口（加水印）
        /// </summary>
        /// <param name="image">Base64字符编码图片</param>
        /// <param name="Extension">扩展名</param>
        /// <param name="WaterMarkContent">水印文字</param>
        /// <returns></returns>
        public static ImageModel UploadImagFileWaterMark(string image, string Extension,string WaterMarkContent)
        {
            string returnPath = "upFile/";
            string filePath = HttpContext.Current.Server.MapPath("~/upFile"); //上传目录
            //string filePath = "http://shtdj.shanhaitian.gov.cn/AppInterface/upFile"; //上传目录
            if (!filePath.EndsWith("/")) filePath += "/";
            string fileName = StringHelper.NewID + "logo" + Extension;
            string nowDate = DateTime.Now.ToString("yyyy/MM/dd/");

            filePath += nowDate;
            returnPath += nowDate + fileName;
            string newPath = filePath + "/" + "new" + fileName;
            string returnNewPath = "upFile/" + nowDate + "new" + fileName;
            string FullfileName = filePath + "/" + fileName;

            //图片转换
            string base64 = image.Replace("data:image/jpeg;base64,", "").Replace("data:image/jpg;base64,", "");

            byte[] imageByte = Convert.FromBase64String(base64);

            if (!Directory.Exists(filePath))//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(filePath);
            }
            //保存
            File.WriteAllBytes(FullfileName, imageByte);
            ImageWaterMark imageWater = new ImageWaterMark();
            //加水印
            imageWater.AddWaterMarkText(FullfileName, newPath, WaterMarkType.TextMark, WaterMarkContent);

            return new ImageModel()
            {
                ImageName = fileName,
                ImageUrl = returnNewPath
            };
        }
        #endregion

        public static string GetFileUrlNew(string fileID)
        {
            string strSql = "SELECT url FROM tblpartyfile WHERE ID = '" + fileID + "'";
            object obj = ZHDJ.Data.MySqlHelper.ExecuteScalar(strSql);
            if (obj == null)
                return "";
            else
                return obj.ToString();
        }

        #region 网站地址的域名
        /// <summary>
        /// 网站地址的域名
        /// </summary>
        public static string AppAddress
        {
            get
            {
                return ServiceSettings.AppAddress;
            }
        }
        public static string AppAddressEx
        {
            get
            {
                return ServiceSettings.AppAddressEx;
            }
        }
        public static string AppAddressNote
        {
            get
            {
                return ServiceSettings.AppAddressNote;
            }
        }
        #endregion

        #region 文件根目录
        public static string FileServerRootUrl
        {
            get
            {
                string str = ServiceSettings.FileUploadUrl;
                if (str.EndsWith("/"))
                {
                    str = str.Substring(0, str.Length - 1);
                }
                int length = str.LastIndexOf('/');
                return str.Substring(0, length);
            }
        }
        #endregion

        #region MD5加密
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public static string GetMD5(string strSource)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSource, "MD5").ToLower();
        }
        #endregion

        #region 根据日期计算日期周数
        /// <summary>
        /// 根据日期计算日期周数
        /// </summary>
        /// <param name="type">1 周一为一周的第一天; 否则以周日为一周的第一天 </param>
        /// <param name="date"></param>
        /// <returns></returns>
        public static int WeekOfYear(string type, DateTime date)
        {
            DayOfWeek dw = (Convert.ToDateTime(string.Format("{0}-1-1 0:0:0", date.Year.ToString()))).DayOfWeek;
            int day = 0;
            if (type == "1")
            {
                switch (dw)
                {

                    case DayOfWeek.Monday:
                        {
                            day = -1;
                            break;
                        }
                    case DayOfWeek.Tuesday:
                        {
                            day = 0;
                            break;
                        }
                    case DayOfWeek.Wednesday:
                        {
                            day = 1;
                            break;
                        }
                    case DayOfWeek.Thursday:
                        {
                            day = 2;
                            break;
                        }
                    case DayOfWeek.Friday:
                        {
                            day = 3;
                            break;
                        }
                    case DayOfWeek.Saturday:
                        {
                            day = 4;
                            break;
                        }
                    case DayOfWeek.Sunday:
                        {
                            day = 5;
                            break;
                        }
                }
                int week = (date.DayOfYear + day) / 7 + 1;

                return week;
            }
            else
            {
                switch (dw)
                {
                    case DayOfWeek.Sunday:
                        {
                            day = -1;
                            break;
                        }
                    case DayOfWeek.Monday:
                        {
                            day = 0;
                            break;
                        }
                    case DayOfWeek.Tuesday:
                        {
                            day = 1;
                            break;
                        }
                    case DayOfWeek.Wednesday:
                        {
                            day = 2;
                            break;
                        }
                    case DayOfWeek.Thursday:
                        {
                            day = 3;
                            break;
                        }
                    case DayOfWeek.Friday:
                        {
                            day = 4;
                            break;
                        }
                    case DayOfWeek.Saturday:
                        {
                            day = 5;
                            break;
                        }
                }
                int week = (date.DayOfYear + day) / 7 + 1;

                return week;
            }
        }
        #endregion

        #region 发帖,回帖内容表情替换
        public static string ReplaceForumConten(string content)
        {
            string sql = string.Format(@" select * from tblMSFeelings ");
            DataSet ds = ZHDJ.Data.MySqlHelper.ExecuteDataSet(sql);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    content = content.Replace(dr["Feelings"].ToString(), dr["ReplaceObj"].ToString());
                }
            }

            return content;
        }
        #endregion

        #region 组织名称转换
        public static string ChangeBranchName(string branchName)
        {
            if (branchName == "区委")
                branchName = "智慧党建网";

            return branchName;
        }
        #endregion

        #region 取小图片
        public static string GetSmallImg(string imgUrl)
        {
            if (!string.IsNullOrEmpty(Path.GetExtension(imgUrl)))
                return imgUrl.Replace(Path.GetExtension(imgUrl), string.Format("_small{0}", Path.GetExtension(imgUrl)));

            return imgUrl;
        }
        public static string GetSmallImgEx(string imgUrl)
        {
            if (!string.IsNullOrEmpty(Path.GetExtension(imgUrl)))
                return imgUrl.Replace(Path.GetExtension(imgUrl), string.Format("_small{0}", Path.GetExtension(imgUrl)));

            return imgUrl;
        }
        #endregion


        /// <summary>
        /// 获取文件url
        /// </summary>
        /// <param name="fileID"></param>
        /// <returns></returns>
        public static string GetFileUrl(string fileID)
        {
            using (var DB = new DBInstance().DB)
            {
                var url = "";
                var file = DB.PartyFiles.Find(fileID);
                if (file == null)
                {
                    return "";
                }
                var sysPara = SystemParameterCaching.Get(SystemParameterKey.UploadFileHost);
                if (!string.IsNullOrEmpty(sysPara))
                {
                    url = sysPara + "/" + file.Url;
                }
                else
                {
                    url = file.Url;
                }
                return url;
            }
        }

        #region 图片加域名
        /// <summary>
        /// 图片地址加域名
        /// </summary>
        /// <param name="html">文章内容</param>
        /// <returns></returns>
        public static string AddHostToImgUrl(string html, string host)
        {
            string regstr = @"<IMG[^>]+src=\s*(?:'(?<src>[^']+)'|""(?<src>[^""]+)""|(?<src>[^>\s]+))\s*[^>]*>";

            Regex r = new Regex(regstr, RegexOptions.IgnoreCase);
            MatchEvaluator evaluator = new MatchEvaluator(ConvertAddHost);
            var rs = r.Replace(html, evaluator);
            return rs;
        }

        private static string ConvertAddHost(Match match)
        {
            return match.Value.ToLower().Replace(match.Groups["src"].Value.ToLower(), CommonUtils.AppAddress + match.Groups["src"].Value.ToLower());
        }
        #endregion
        public static bool IsDisableUsers(string loginID)
        {
            string strUsers = ServiceSettings.DisableUsers;
            if (!string.IsNullOrEmpty(strUsers))
            {
                string[] users = strUsers.Split(';');
                foreach (string item in users)
                {
                    if (loginID.ToLower().Equals(item.ToLower()))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        ///   <summary>   
        ///   去除HTML标记   
        ///   </summary>   
        ///   <param   name="NoHTML">包括HTML的源码   </param>   
        ///   <returns>已经去除后的文字</returns>   
        public static string NoHTML(string Htmlstring)
        {
            //删除脚本   
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML   
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&rdquo;", "   ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&ldquo;", "   ", RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

            return Htmlstring;
        }

        /// <summary>
        /// 复制DataTable
        /// </summary>
        /// <param name="dtOld"></param>
        /// <returns></returns>
        public static DataTable CopyDataTable(DataTable dtOld)
        {
            DataTable dtNew = dtOld.Copy();
            dtNew.Clear();
            for (int i = 0; i < dtOld.Rows.Count; i++)
            {
                dtNew.Rows.Add(dtOld.Rows[i].ItemArray);
            }
            return dtNew;
        }
    }
}